package ${packagePath};

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;

/**
 * @author cxx
 **/
public class DateUtil {

    private DateUtil() {
        throw new IllegalStateException("Utility class");
    }

    public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    public static long getTimestampOfDateTime(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        return instant.toEpochMilli();
    }

    public static String getSimpleDate(LocalDateTime localDateTime){
        SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy.MM.dd HH:mm:ss");
        return dateFormat.format (new Date (getTimestampOfDateTime (localDateTime)));
    }

    public static Date getDate(LocalDateTime localDateTime){
        return new Date (getTimestampOfDateTime (localDateTime));
    }


    public static String getStrDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMdd");
        return sdf.format (date);
    }

    public static String getGenDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMdd HH:mm:ss");
        return sdf.format (date);
    }

    public static long getTomorrowTimestamp(long ms) {
        LocalDateTime dateTime = getDateTimeOfTimestamp (ms);
        LocalDateTime tomorrow = dateTime.withDayOfMonth (dateTime.getDayOfMonth () + 1)
                .withHour (0)
                .withMinute (0)
                .withSecond (0)
                .withNano (0);
        return getTimestampOfDateTime(tomorrow);
    }

    public static Date getTargetDay(Date current,int target) {
        LocalDateTime dateTime = getDateTimeOfTimestamp (current.getTime ());
        LocalDateTime targetTime = dateTime
                .withHour (0)
                .withMinute (0)
                .withSecond (0)
                .withNano (0);
        targetTime = targetTime.minus (target, ChronoUnit.DAYS);
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = targetTime.atZone(zoneId);
        Date date = Date.from(zdt.toInstant());
        return date;
    }

    public static Date getZeroClockDate(long time) {
        LocalDateTime dateTime = getDateTimeOfTimestamp (time);
        LocalDateTime zeroDate = dateTime.withHour (0)
                .withMinute (0)
                .withSecond (0)
                .withNano (0);
        return getDate (zeroDate);
    }
}
